// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.SourcingManage;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.DevelopmentTaskMapper;
import com.fowo.api.mapper.PurchaseSamplesMapper;
import com.fowo.api.mapper.SourcingManageMapper;
import com.fowo.api.model.development.task.DevelopmentTaskItemVo;
import com.fowo.api.model.development.task.DevelopmentTaskSearchParamPo;
import com.fowo.api.model.purchase.samples.PurchaseSamplesSearchParamPo;
import com.fowo.api.model.sourcing.manage.SourcingManageBatchCompletionAction;
import com.fowo.api.model.sourcing.manage.SourcingManageExcelPo;
import com.fowo.api.model.sourcing.manage.SourcingManageImportPo;
import com.fowo.api.model.sourcing.manage.SourcingManageItemVo;
import com.fowo.api.model.sourcing.manage.SourcingManageSNoIncompleteAction;
import com.fowo.api.model.sourcing.manage.SourcingManageSearchParamPo;
import com.fowo.api.model.sourcing.manage.SourcingManageVo;
import com.fowo.api.model.sourcing.manage.constant.SourcingManageStateEnums;
import com.fowo.api.service.PurchaseSamplesService;
import com.fowo.api.service.SourcingManageService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 寻源管理 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王心成，王阳阳
 */
@Slf4j
@DS("ds24")
public class SourcingManageBaseServiceImpl
  extends ServiceImpl<SourcingManageMapper, SourcingManage>
  implements SourcingManageService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("taskIdTaskId", "dt.`task_id`");
      put("sourcingPersonnelName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected PurchaseSamplesService purchaseSamplesService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected DevelopmentTaskMapper developmentTaskMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private WorkFlowService workFlowService;

  @Autowired(required = false)
  protected SourcingManageSNoIncompleteAction sourcingManageSNoIncompleteAction;

  @Autowired(required = false)
  protected SourcingManageBatchCompletionAction sourcingManageBatchCompletionAction;

  @Resource
  protected Validator validator;

  /**
   * 创建寻源管理
   * @param model 寻源管理
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SourcingManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SourcingManage entity = new SourcingManage();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getState() == null) {
      entity.setState("0");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("寻源管理保存失败");
  }

  /**
   * 更新所有子表
   * @param model 寻源管理
   */
  protected void updateAllChilds(SourcingManageVo model) throws Exception {
    if (model.getPurchaseSamplesId() != null) {
      purchaseSamplesService.saveAllByParentSourcingManage(
        model.getId(),
        model.getPurchaseSamplesId()
      );
    }
  }

  /**
   * 更新寻源管理
   * @param model 寻源管理
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SourcingManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SourcingManage entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("寻源管理不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新寻源管理（带空值）
   * @param model 寻源管理
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SourcingManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SourcingManage entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("寻源管理不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(SourcingManage::getTaskId, model.getTaskId())
      .set(SourcingManage::getSourcingTime, model.getSourcingTime())
      .set(SourcingManage::getSourcingPersonnel, model.getSourcingPersonnel())
      .set(SourcingManage::getLastUpdateTime, model.getLastUpdateTime())
      .set(SourcingManage::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        SourcingManage::getDealerClassification,
        model.getDealerClassification()
      )
      .set(
        SourcingManage::getIncompleteCompletionReason,
        model.getIncompleteCompletionReason()
      )
      .set(SourcingManage::getRemark, model.getRemark())
      .set(SourcingManage::getWorkBadge, model.getWorkBadge())
      .set(SourcingManage::getDealerIndustry, model.getDealerIndustry())
      .set(SourcingManage::getEnterpriseId, model.getEnterpriseId())
      .set(
        SourcingManage::getEnterpriseAbbreviation,
        model.getEnterpriseAbbreviation()
      )
      .set(SourcingManage::getEnterpriseName, model.getEnterpriseName())
      .set(SourcingManage::getSocialCreditCode, model.getSocialCreditCode())
      .set(SourcingManage::getRegisteredCapital, model.getRegisteredCapital())
      .set(SourcingManage::getBusinessScope, model.getBusinessScope())
      .set(SourcingManage::getAddress, model.getAddress())
      .set(SourcingManage::getIfSourceFactory, model.getIfSourceFactory())
      .set(SourcingManage::getDesigners, model.getDesigners())
      .set(SourcingManage::getTypesetter, model.getTypesetter())
      .set(
        SourcingManage::getProductionSchedulingPersonnel,
        model.getProductionSchedulingPersonnel()
      )
      .set(
        SourcingManage::getProductionPersonnel,
        model.getProductionPersonnel()
      )
      .set(
        SourcingManage::getFinancialAdministrativePersonnel,
        model.getFinancialAdministrativePersonnel()
      )
      .set(
        SourcingManage::getProcessManufacturingCapacity,
        model.getProcessManufacturingCapacity()
      )
      .set(SourcingManage::getFixedAssets, model.getFixedAssets())
      .set(SourcingManage::getCurrentAssets, model.getCurrentAssets())
      .set(
        SourcingManage::getReceivablePayableAccounts,
        model.getReceivablePayableAccounts()
      )
      .set(SourcingManage::getInventoryStatus, model.getInventoryStatus())
      .set(SourcingManage::getEnterprise, model.getEnterprise())
      .set(SourcingManage::getLegalPerson, model.getLegalPerson())
      .set(
        SourcingManage::getIntellectualProperty,
        model.getIntellectualProperty()
      )
      .set(
        SourcingManage::getProductCostQuestionnaire,
        model.getProductCostQuestionnaire()
      )
      .set(SourcingManage::getBossIDCopyCard, model.getBossIDCopyCard())
      .set(
        SourcingManage::getQualitySystemCertification,
        model.getQualitySystemCertification()
      )
      .set(SourcingManage::getDevice, model.getDevice())
      .set(SourcingManage::getWorkShop, model.getWorkShop())
      .set(SourcingManage::getLivePictures, model.getLivePictures())
      .set(
        SourcingManage::getIndustryMandatoryCertification,
        model.getIndustryMandatoryCertification()
      )
      .set(SourcingManage::getBusinessLicense, model.getBusinessLicense())
      .set(SourcingManage::getPatrolPhotography, model.getPatrolPhotography())
      .set(SourcingManage::getContractTemplate, model.getContractTemplate())
      .eq(SourcingManage::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(SourcingManageSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 寻源管理子表(purchaseSamplesId) 对应的对象
    PurchaseSamplesSearchParamPo purchaseSamplesIdSearchParam =
      new PurchaseSamplesSearchParamPo();
    purchaseSamplesIdSearchParam.setDisableDataPremissions(true);
    purchaseSamplesIdSearchParam.setParentSourcingManageInList(ids);
    PurchaseSamplesMapper localPurchaseSamplesMapper = ContextHolder
      .getApplicationContext()
      .getBean(PurchaseSamplesMapper.class);
    purchaseSamplesIdSearchParam.applySqlSegments();
    List<Long> purchaseSamplesIdIdList = localPurchaseSamplesMapper.searchIds(
      purchaseSamplesIdSearchParam
    );
    if (!purchaseSamplesIdIdList.isEmpty()) {
      PurchaseSamplesService localPurchaseSamplesService = ContextHolder
        .getApplicationContext()
        .getBean(PurchaseSamplesService.class);
      localPurchaseSamplesService.batchDelete(purchaseSamplesIdIdList);
    }
  }

  /**
   * 删除寻源管理
   * @param id 寻源管理的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除寻源管理
   * @param ids 寻源管理的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<SourcingManageImportPo> excelToImportRow(
    SourcingManageImportPo row,
    Integer rowNumber,
    SourcingManageVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<SourcingManageImportPo> ir =
      new ImportRow<SourcingManageImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<SourcingManageImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new SourcingManageVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, SourcingManageImportPo.class);

    // 一般数据处理
    vo.setSourcingTime(SheetUtils.tryToDateTime(row.getSourcingTime()));
    if (StringUtils.hasText(row.getDealerClassification())) {
      List<SysDictAllItem> dealerClassificationItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "dealerClassification",
          n -> sysDictService.getDictItems("SCM107")
        );
      SourcingManageVo finalVo = vo;
      dealerClassificationItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getDealerClassification()))
        .findFirst()
        .ifPresent(i -> finalVo.setDealerClassification(i.getItemValue()));
    }
    if (StringUtils.hasText(row.getState())) {
      vo.setState(SourcingManageStateEnums.toValue(row.getState()));
      if (vo.getState() == null) {
        ir.addError("state", "状态只能是：“接收”, “未完成”, “完成”, “已失效”");
      }
    }
    vo.setWorkBadge(SheetUtils.tryToLong(row.getWorkBadge()));
    vo.setEnterpriseId(SheetUtils.tryToLong(row.getEnterpriseId()));
    vo.setSocialCreditCode(SheetUtils.tryToLong(row.getSocialCreditCode()));
    vo.setRegisteredCapital(SheetUtils.tryToLong(row.getRegisteredCapital()));
    vo.setIfSourceFactory(SheetUtils.tryToBoolean(row.getIfSourceFactory()));
    vo.setTaskItemId(SheetUtils.tryToLong(row.getTaskItemId()));
    // 处理关联字段“开发任务编号”
    if (
      !SheetUtils.isBlank(row.getTaskIdTaskId()) &&
      SheetUtils.isBlank(row.getTaskId())
    ) {
      DevelopmentTaskSearchParamPo taskIdSearchParam =
        new DevelopmentTaskSearchParamPo();
      taskIdSearchParam.setLimit(2); // 最大只返回二行记录
      taskIdSearchParam.setTaskIdEq(SheetUtils.trim(row.getTaskIdTaskId()));
      taskIdSearchParam.applySqlSegments();
      List<DevelopmentTaskItemVo> taskIdMatches = developmentTaskMapper.search(
        taskIdSearchParam
      );
      if (taskIdMatches.size() == 0) {
        ir.addError("taskIdTaskId", "未能在开发任务中找到匹配的数据");
      } else if (taskIdMatches.size() > 1) {
        ir.addError(
          "taskIdTaskId",
          "关联不唯一，在开发任务中找到多个匹配的数据"
        );
      } else {
        vo.setTaskId(taskIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“寻源人员”
    if (
      !SheetUtils.isBlank(row.getSourcingPersonnelName()) &&
      SheetUtils.isBlank(row.getSourcingPersonnel())
    ) {
      SysUserSearch sourcingPersonnelSearchParam = new SysUserSearch();
      sourcingPersonnelSearchParam.setLimit(2); // 最大只返回二行记录
      sourcingPersonnelSearchParam.setNameEq(
        SheetUtils.trim(row.getSourcingPersonnelName())
      );
      sourcingPersonnelSearchParam.applySqlSegments();
      List<SysUserItemVo> sourcingPersonnelMatches = sysUserMapper.search(
        sourcingPersonnelSearchParam
      );
      if (sourcingPersonnelMatches.size() == 0) {
        ir.addError("sourcingPersonnelName", "未能在用户中找到匹配的数据");
      } else if (sourcingPersonnelMatches.size() > 1) {
        ir.addError(
          "sourcingPersonnelName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setSourcingPersonnel(
          sourcingPersonnelMatches
            .stream()
            .map(SysUserItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<SourcingManageImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<SourcingManageImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            SourcingManageImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              SourcingManageImportPo row,
              AnalysisContext cxt
            ) {
              SourcingManageVo vo = new SourcingManageVo();
              ImportRow<SourcingManageImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<SourcingManageImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<SourcingManageImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      SourcingManageVo vo = new SourcingManageVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    SourcingManageSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "taskId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((SourcingManageItemVo) r).getTaskIdTaskId())
          )
      );
      exportOptions.addFieldMappingOption(
        "dealerClassification",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM107")
      );
      exportOptions.addFieldMappingOption(
        "state",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> SourcingManageStateEnums.toLabel((String) o))
      );
      exportOptions.addStringFields(
        "taskIdTaskId",
        "dealerClassification",
        "state",
        "dealerIndustry",
        "enterpriseAbbreviation",
        "enterpriseName",
        "businessScope",
        "address",
        "ifSourceFactory",
        "designers",
        "typesetter",
        "productionSchedulingPersonnel",
        "productionPersonnel",
        "financialAdministrativePersonnel",
        "processManufacturingCapacity",
        "fixedAssets",
        "currentAssets",
        "receivablePayableAccounts",
        "inventoryStatus",
        "enterprise",
        "legalPerson"
      );

      String fileName = String.format(
        "寻源管理(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> dealerClassificationItems =
      sysDictService.getDictItems("SCM107");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SourcingManageExcelPo> items = new ArrayList<SourcingManageExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<SourcingManageItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SourcingManageItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SourcingManageItemVo item : list) {
        SourcingManageExcelPo excel = new SourcingManageExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getDealerClassification() != null) {
          dealerClassificationItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getDealerClassification())
            )
            .findFirst()
            .ifPresent(i -> excel.setDealerClassification(i.getItemText()));
        }
        excel.setState(SourcingManageStateEnums.toLabel(item.getState()));
        if (item.getIfSourceFactory() != null) {
          excel.setIfSourceFactory(item.getIfSourceFactory() ? "是" : "否");
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "寻源管理(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SourcingManageExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过开发任务编号查询寻源管理主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByTaskId(Long taskId) {
    return this.baseMapper.getIdByTaskId(taskId);
  }

  /**
   * 通过开发任务编号查询寻源管理多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByTaskId(List<Long> list) {
    return this.baseMapper.getIdsByTaskId(list);
  }

  /**
   * 通过寻源管理主键查询开发任务编号
   */
  @Override
  public Long getTaskIdById(Long id) {
    return this.baseMapper.getTaskIdById(id);
  }

  /**
   * 通过寻源管理主键查询开发任务编号列表
   */
  @Override
  public List<Long> getTaskIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getTaskIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (Long) stringObjectMap.get("taskId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 寻源管理的主键
   */
  @Override
  public SourcingManageVo getVoById(Long id) throws Exception {
    SourcingManageVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    PurchaseSamplesSearchParamPo purchaseSamplesIdSearchParamPo =
      new PurchaseSamplesSearchParamPo();
    purchaseSamplesIdSearchParamPo.setParentSourcingManage(id);
    purchaseSamplesIdSearchParamPo.applySqlSegments();
    vo.setPurchaseSamplesId(
      purchaseSamplesService.search(purchaseSamplesIdSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询寻源管理
   * @param search 查询条件
   * @return 寻源管理分页查询结果
   */
  @Override
  public Page<SourcingManageItemVo> pageSearch(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 寻源管理快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SourcingManageOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SourcingManageItemVo>> searchOptions(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询寻源管理
   * @param search 查询条件
   * @return 寻源管理列表查询结果
   */
  @Override
  public List<SourcingManageItemVo> search(SourcingManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询寻源管理最后更新时间
   * @param search 查询条件
   * @return 寻源管理最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 批量未完成
   */
  @Override
  public void sNoIncomplete(List<Long> ids) throws Exception {
    if (sourcingManageSNoIncompleteAction == null) {
      throw new Exception("此操作当前不可用");
    }
    sourcingManageSNoIncompleteAction.run(ids);
  }

  /**
   * 批量完成
   */
  @Override
  public void batchCompletion(List<Long> ids) throws Exception {
    if (sourcingManageBatchCompletionAction == null) {
      throw new Exception("此操作当前不可用");
    }
    sourcingManageBatchCompletionAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    SourcingManageSearchParamPo search = new SourcingManageSearchParamPo();
    return MapUtil
      .builder()
      .put("AllData", this.baseMapper.allDataCount(search))
      .put("Receive", this.baseMapper.receiveCount(search))
      .put("Complete", this.baseMapper.completeCount(search))
      .put("NoIncomplete", this.baseMapper.noIncompleteCount(search))
      .put("Expired", this.baseMapper.expiredCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<SourcingManageItemVo> allData(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allData(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<SourcingManageItemVo> allDataPage(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> allDataPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allDataPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allDataPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allDataPage = this.baseMapper.allDataPage(search.toPage(), search);
    List<Long> recordIds = allDataPage
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allDataPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allDataPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allDataPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allDataPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allDataLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.allDataLastUpdateTime(search);
  }

  /**
   * 接收
   */
  @Override
  public List<SourcingManageItemVo> receive(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.receive(search);
  }

  /**
   * 接收分页
   */
  @Override
  public Page<SourcingManageItemVo> receivePage(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> receivePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return receivePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return receivePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    receivePage = this.baseMapper.receivePage(search.toPage(), search);
    List<Long> recordIds = receivePage
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return receivePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return receivePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    receivePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return receivePage;
  }

  /**
   * 查询接收最后更新时间
   * @param search 查询条件
   * @return 接收最后更新时间
   */
  @Override
  public Date receiveLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.receiveLastUpdateTime(search);
  }

  /**
   * 完成
   */
  @Override
  public List<SourcingManageItemVo> complete(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.complete(search);
  }

  /**
   * 完成分页
   */
  @Override
  public Page<SourcingManageItemVo> completePage(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> completePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completePage = this.baseMapper.completePage(search.toPage(), search);
    List<Long> recordIds = completePage
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completePage;
  }

  /**
   * 查询完成最后更新时间
   * @param search 查询条件
   * @return 完成最后更新时间
   */
  @Override
  public Date completeLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.completeLastUpdateTime(search);
  }

  /**
   * 未完成
   */
  @Override
  public List<SourcingManageItemVo> noIncomplete(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.noIncomplete(search);
  }

  /**
   * 未完成分页
   */
  @Override
  public Page<SourcingManageItemVo> noIncompletePage(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> noIncompletePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return noIncompletePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return noIncompletePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    noIncompletePage =
      this.baseMapper.noIncompletePage(search.toPage(), search);
    List<Long> recordIds = noIncompletePage
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return noIncompletePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return noIncompletePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    noIncompletePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return noIncompletePage;
  }

  /**
   * 查询未完成最后更新时间
   * @param search 查询条件
   * @return 未完成最后更新时间
   */
  @Override
  public Date noIncompleteLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.noIncompleteLastUpdateTime(search);
  }

  /**
   * 已失效
   */
  @Override
  public List<SourcingManageItemVo> expired(
    SourcingManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.expired(search);
  }

  /**
   * 已失效分页
   */
  @Override
  public Page<SourcingManageItemVo> expiredPage(
    SourcingManageSearchParamPo search
  ) {
    Page<SourcingManageItemVo> expiredPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return expiredPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return expiredPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    expiredPage = this.baseMapper.expiredPage(search.toPage(), search);
    List<Long> recordIds = expiredPage
      .getRecords()
      .stream()
      .map(SourcingManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return expiredPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return expiredPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    expiredPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return expiredPage;
  }

  /**
   * 查询已失效最后更新时间
   * @param search 查询条件
   * @return 已失效最后更新时间
   */
  @Override
  public Date expiredLastUpdateTime(SourcingManageSearchParamPo search) {
    return this.baseMapper.expiredLastUpdateTime(search);
  }
}
